package com.skivingcloud.admin.sys.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.skivingcloud.admin.sys.entity.SysTenant;
import com.skivingcloud.admin.sys.entity.SysTenantMenu;
import com.skivingcloud.admin.sys.mapper.SysTenantMenuMapper;
import com.skivingcloud.admin.sys.service.SysTenantMenuService;
import com.skivingcloud.common.utils.UuidUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 *  服务层实现。
 *
 * @author skivingcloud
 * @since 2023-08-28
 */
@Service
public class SysTenantMenuServiceImpl extends ServiceImpl<SysTenantMenuMapper, SysTenantMenu> implements SysTenantMenuService {
    
    /**
     * 根据租户id查询租户的菜单权限范围
     *
     * @param tenantId 租户id
     * @return 租户资源关系
     */
    @Override
    public List<SysTenantMenu> getResTreeByTenantId(String tenantId){
        QueryWrapper queryWrapper = QueryWrapper.create().where(SysTenantMenu::getTenantId).eq(tenantId);
        return this.mapper.selectListByQuery(queryWrapper);
    }
    
    /**
     * 设置租户资源权限
     *
     * @param tenant 租户资源权限信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setSysTenantMenu(SysTenant tenant){
        String[] res = tenant.getResId();
        QueryWrapper queryWrapper = QueryWrapper.create().where(SysTenantMenu::getTenantId).eq(tenant.getId());
        this.mapper.deleteByQuery(queryWrapper);
        this.mapper.insertBatch(Arrays.stream(res).map(m -> {
            SysTenantMenu sysTenantMenu = new SysTenantMenu();
            sysTenantMenu.setId(UuidUtil.get32UUID());
            sysTenantMenu.setTenantId(tenant.getId());
            sysTenantMenu.setMenuId(m);
            return sysTenantMenu;
        }).toList());
    }
}
